package com.zm.study.common;

import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * <p></p>
 *
 * @author zoulei
 * @version $Id: TOTransferHelper.java, v 0.1 2018-03-18 下午2:20 zoulei$$
 */
public class TOTransferHelper {


    private static final Logger LOGGER = LoggerFactory.getLogger(TOTransferHelper.class);

    public static <D, T> List<D> trans(List<T> tos, Class clazz) {
        if (CollectionUtils.isEmpty(tos))
            return Collections.emptyList();

        List<D> domains = new LinkedList<>();
        for (T to : tos) {
            D domain = trans(to, clazz);
            domains.add(domain);
        }

        return domains;
    }

    public static <D, T> D trans(T to, Class clazz) {
        D domain = (D) newT(clazz);
        try {
            BeanUtils.copyProperties(domain, to);
        } catch (IllegalAccessException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return domain;
    }

    public static <D, T> List<T> trans2TO(List<D> domains, Class clazz) {
        if (CollectionUtils.isEmpty(domains))
            return Collections.emptyList();

        List<T> tos = new LinkedList<>();

        for (D domain : domains) {
            T to = trans2TO(domain, clazz);
            tos.add(to);
        }

        return tos;
    }

    public static <D, T> T trans2TO(D domain, Class clazz) {
        T to = (T) newT(clazz);
        String json = JSON.toJSONString(domain);
        to = (T) JSON.parseObject(json, clazz);
        return to;
    }

    private static <T> T newT(Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (InstantiationException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IllegalAccessException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return t;
    }

}
